import {defineStore} from 'pinia'
import {setStore, getStore} from '/src/utils/store.js'
import dayjs from 'dayjs'
import {sendLogs} from '/src/api/user.js'

export const useLogsStore = defineStore('logs', () => {
  const logsList = ref(getStore({name: 'logsList'}) || [])

  const logsLen = computed(() => {
    return logsList.value.length || 0
  })
  const logsFlag = computed(() => {
    return logsLen.value === 0
  })

  //发送错误日志
  async function SendLogs() {
    return new Promise((resolve, reject) => {
      sendLogs(logsList.value).then(() => {
        CLEAR_LOGS();
        resolve();
      }).catch(error => {
        reject(error)
      })
    })
  }


  function ADD_LOGS({type, message, stack, info}) {
    logsList.value.push(Object.assign({
      url: window.location.href,
      time: dayjs().format('YYYY-MM-DD HH:mm:ss')
    }, {
      type,
      message,
      stack,
      info: info.toString()
    }))
    setStore({name: 'logsList', content: logsList.value})
  }

  function CLEAR_LOGS() {
    logsList.value = [];
    setStore({name: 'logsList', content: logsList.value})
  }

  return {
    logsList, logsLen, logsFlag, SendLogs, ADD_LOGS, CLEAR_LOGS
  }
})

